import * as mongoose from 'mongoose'
import * as validator from 'validator'

const collectionSchema = new mongoose.Schema({
  type: String,
  content: String,
  createTime: Date,
  lastUpdateTime: Date,
})

class CollectionClass extends mongoose.Model {
  public static async get({ id }) {
    const coll = await this.findById(mongoose.Types.ObjectId(id))

    if (!coll) {
      throw new Error('找不到啊我的小老弟')
    }

    return coll
  }

  public static async add({ content, type }) {
    if (!['json', 'page'].includes(type)) {
      throw new Error('小兄弟好好看看你的type')
    }

    if (!content) {
      throw new Error('你的content跑哪去了')
    }

    if (!validator.isJSON(content)) {
      throw new Error('这不是JSON吧小老弟')
    }

    const collection = await this.create({
      type,
      content,
      createTime: new Date(),
    })

    return collection
  }

  public static async delete({ id }) {
    const coll = await this.findById(mongoose.Types.ObjectId(id))

    if (!coll) {
      throw new Error('已经没有这个Collection了小老弟')
    }

    await this.findByIdAndDelete(id)
  }
}

collectionSchema.loadClass(CollectionClass)

interface CollectionDocument extends mongoose.Document {
  type: string
  content: string
  createdTime: Date
  lastUpdateTime: Date
}

interface CollectionModel extends mongoose.Model<CollectionDocument> {
  add({ content, type }): Promise<CollectionDocument>
  get({ id }): Promise<CollectionDocument>
  delete({ id }): Promise<void>
}

const Collection = mongoose.model<CollectionDocument, CollectionModel>(
  'Collection',
  collectionSchema
)

export default Collection
